/**
 * 
 */
package com.ebao.gs.integration.sms;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.LinkedList;
import java.util.List;

import javax.sql.DataSource;

import org.apache.log4j.Logger;
import org.springframework.core.io.Resource;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author ralph.jiang
 * 
 */
public class DefaultSMSSchemaService implements SMSSchemaService {

	private static final Logger logger = Logger
			.getLogger(DefaultSMSSchemaService.class);
	private Resource schemaSql;
	private DataSource dataSource;

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.ebao.gs.integration.sms.SMSSchemaService#createSchema()
	 */
	@Transactional
	public void createSchema() {
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		try {
			conn = dataSource.getConnection();
			DatabaseMetaData meta = conn.getMetaData();
			rs = meta.getTables(null, null, "T_SMS", new String[] { "TABLE" });
			if (rs.next()) {
				logger.info("The SMS table schema has been created before.");
				return;
			}
			rs.close();
			rs = null;
			List<String> sqls = loadSchemaSQL();
			int rows = sqls.size();
			if (!sqls.isEmpty()) {
				stmt = conn.createStatement();
				for (String sql : sqls) {
					if (logger.isDebugEnabled()) {
						logger.debug("processing sql => " + sql);
					}
					if(sql.endsWith(";")){
						sql = sql.substring(0, sql.length()-1);
					}
					stmt.executeUpdate(sql);
				}
			}
			logger.info(rows + " rows executed.");
		} catch (Exception e) {
			logger.error("create schema fail.", e);
		} finally {
			if (null != rs) {
				try {
					rs.close();
				} catch (SQLException e) {

				}
			}
			if (null != stmt) {
				try {
					stmt.close();
				} catch (SQLException e) {

				}
			}
			if (null != conn) {
				try {
					conn.close();
				} catch (SQLException e) {

				}
			}
		}
	}
	protected List<String> loadSchemaSQL() throws IOException {
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new InputStreamReader(
					schemaSql.getInputStream(), "UTF-8"));

			String s = null;
			List<String> result = new LinkedList<String>();

			while ((s = reader.readLine()) != null) {
				result.add(s);
			}
			return result;
		} finally {
			if (null != reader) {
				try {
					reader.close();
				} catch (IOException e) {

				}
			}
		}
	}

	public Resource getSchemaSql() {
		return schemaSql;
	}

	public void setSchemaSql(Resource schemaSql) {
		this.schemaSql = schemaSql;
	}

	public DataSource getDataSource() {
		return dataSource;
	}

	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
	}

}
